<template>
<view class="pro-body">
	<view class="fixed-header">
	<view class="uni-form-item uni-column">
	    <view class="search-box">
	        <input class="uni-input" confirm-type="search" placeholder="输入生产订单号/客户订单号" v-model="billNo"  @confirm="onSearch"/>
	    </view>
		<view class="scan-icon" @click="scanOrderDe()">
		  <image src="/static/img/scan.png" style="width: 70px; height: 70px; margin-left: 10px;"class="search-icon-image"></image>
		</view>
	</view>
	
	<view class="section">  
	    <view class="section__title">日期:</view>  
	          <picker mode="date" :value="startDate" :start="startDateLimit" :end="endDateLimit" @change="onStartDateChange">  
	        <view class="picker-container">  
	           <text class="picker-text">{{ formatDate(startDate) }}</text>  
	        </view>  
		</picker>  
			<view class="section__title">至</view> 
			 <picker mode="date" :value="endDate" :start="startDateLimit" :end="endDateLimit" @change="onEndDateChange"> 
			    <view class="picker-container">  
			      <text class="picker-text">{{ formatDate(endDate) }}</text>
			    </view>  
	    </picker>  
		<view  class="box-but" >
				 <button class="search-button" @click="onSearch">搜索</button>  
				 <uni-icons :size="35" type="loop" @click="onChongzhi"></uni-icons>  
		</view>  
	</view>
	
 </view>

	<task-order ref="taskOrderRef" @success="handleScanSuccess"></task-order>
	<view class="uni-form-list">
	        <scroll-view scroll-y="true" class="scroll"
	        @scrolltolower="handleScrolltolower" refresher-enabled
	        @refresherrefresh="handleRefresherrefresh" :refresher-triggered="refresherTriggered">
	        	<template v-if="motMap.taskHistoryList && motMap.taskHistoryList.length > 0">
	        		<uni-swipe-action>
	        			<uni-swipe-action-item 
	        				v-for="item in motMap.taskHistoryList">
	        				<view class="panel" @click="openDetail(item)" :style="{ backgroundColor: item.boxColor }">
	        					<view class="panel_title" :class="{error: item.error}">
	        						<view class="panel_title_left">{{ item.fbillno }}</view>
	        						<view class="panel_title_right">{{ item.fprdorgname }}</view>
	        					</view>
	        					<view class="panel_content">
	        						<view class="flex-list">
	        							<view class="flex-left">
	        								<view class="flex-title-row">
	        									<view class="flex-title">编码</view><span>：</span>
	        								</view>
	        								<view class="flex-title-row">
	        									<view class="flex-title">名称</view><span>：</span>
	        								</view>
											<view class="flex-title-row">
												<view class="flex-title">客户订单号</view><span>：</span>
											</view>
	        								<view class="flex-title-row">
	        									<view class="flex-title">规格</view><span>：</span>
	        								</view>
	        							
											<view class="flex-title-row">
												<view class="flex-title">数量</view><span></span>
											</view>
											
											<view class="flex-title-row">
												<view class="flex-title">时间</view><span>：</span>
											</view>
	        							</view>
	        							<view class="flex-right">
	        								<view class="flex-content">
	        									{{ item.fmaterialnumber }}
	        								</view>
	        								<view class="flex-content">
	        									{{ item.fmaterialname }}
	        								</view>
											<view class="flex-content">
												{{ item.fcubillno }}
											</view>
	        								<view class="flex-content">
	        									{{ item.fspecification }}
	        								</view>
											<view class="flex-content">
												{{ item.fqty }}
											</view>
											<view class="flex-content">
												<uni-dateformat :date="item.fcreatedate"
													format="yyyy年MM月dd日">
												</uni-dateformat>
											</view>
	        							</view>
	        						</view>
	        						
	        					</view>
	        				</view>
	        			</uni-swipe-action-item>
	        			<!-- 加载 -->
	        			 <uni-load-more
	        				:status="motMap.pageConfig.bottomLoading ? 'loading' : motMap.pageConfig.bottomEnd ? 'noMore' : 'more'">
	        			</uni-load-more>
	        		</uni-swipe-action>
	        	</template>
	        <!-- <uni-empty-info v-else label="暂无任务信息"></uni-empty-info> -->
	        </scroll-view>
	</view> 
		
</view>
	
</template>

<script>
	import wechat from 'weixin-js-sdk'
	import {getMoListHistory,wxInit} from '@/utils/api.js';
	import TaskOrder from '../../components/popup/task-order.vue'
	export default {
		components: {
			TaskOrder
		},
	  data() {
	  return {
	  	motMap: {
	  		taskHistoryList: [],
	  		pageConfig: {
	  			pageIndex: 0,
	  			pageSize: 20,
	  			bottomEnd: false,
	  			bottomLoading: true
	  		}
	  	 },
		wechat:{},
		refresherTriggered: false,
		_refresherTriggered: false,
		
		billNo: '',    // 订单搜索框的值 
		html5Qrcode: null,
		isScaning: false,
		
		startDate: this.getDefaultStartDate(),
		endDate: this.getDefaultEndDate(),
		startDateLimit: '2000-01-01',
		endDateLimit: new Date().toISOString().slice(0, 10),
	
	  	selectRange: []
	  	
	  	 };
	    },
	  methods: {  
		  //获取微信配置信息
		  getWxConfig(url){
		  	// var url = window.location.href.split('#')[0]
		  	//const url = window.location.href
		  	//const url = encodeURIComponent(location.href.split('#')[0])
		  	//const url = 'http://test2.vtuzx.cn'
		  	//var url = window.location.href.split('#')[0]
		  	console.log(url)
		  	wxInit({'url' :url }).then(res =>{
		  		
		  		this.saveWxConfig(res.data.data)
		  	})
		  },
		  //配置微信config
		  saveWxConfig(res){
		  	// 配置config信息
		  	wechat.config({
		  		debug: false,
		  		appId: res.appid, // 必填，公众号的唯一标识
		  		timestamp: res.timestamp, // 必填，生成签名的时间戳
		  		nonceStr: res.nonceStr, // 必填，生成签名的随机串
		  		signature: res.signature, // 必填，签名
		  		jsApiList: ['scanQRCode'] // 必填，需要使用的JS接口列表
		  	});
		  
		  	// 通过ready接口处理成功验证
		  	wechat.ready(function () {
		  		wechat.checkJsApi({
		  			jsApiList: ['scanQRCode'],
		  			success: function (res) {
		  				console.log('检验成功');
		  			}
		  		});
		  	});
		  	// 通过error接口处理失败验证
		  	wechat.error(function (res) {
		  		console.log('校验失败');
		  	});
		  
		  },
		  /**
		   * 扫描仓位
		   */
	scanOrderDe(){
		wechat.scanQRCode({
			needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果
			scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
			success: (res) => {
			  // 当needResult 为 1 时，扫码返回的结果
			alert(res.resultStr)
			 this.billNo = res.resultStr 
			 //扫码成功后跳转到详情
			 this.taskScanningSucess();
			}
		 });
	},
		
		  handleScanSuccess(scanVal) {
					this.billNo = scanVal
							console.log('11',this.billNo )
					this.taskScanningSucess()
				},

			// 在合适的时机调用 filterOrdersByBillNo 方法，例如在扫描成功后
			taskScanningSucess(e) {
				let self = this;
				console.log('billNo:', self.billNo); //调试信息
				getMoListHistory({
				        billNo: self.billNo || ""
				    }).then(res => {
				        if (res.data.status == 200) {
				            this.$refs.taskOrderRef.close()
							uni.navigateTo({
									   url: '/pages/produce/produceHisDetail?taskBillNo=' + self.billNo+'&FPRDORGID=' + self.fprdorgid,
									
							})
				
					}
					self.$emit('back', true)
				})
			},

		  /**
		   * 订单号日期搜索
		   */
		  onSearch(){
		  	this.initData({
			startDate: this.startDate,
			endDate: this.endDate,
			billNo: this.billNo,
			
			});
		  },
		  onChongzhi() {
		      this.billNo = '';
		      this.startDate = '';
		      this.endDate = '';
		    },
formatDate(date) {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = ('0' + (d.getMonth() + 1)).slice(-2);
    const day = ('0' + d.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
  },
  getDefaultStartDate() {
        const date = new Date();
        date.setDate(date.getDate() - 30);
        return date.toISOString().slice(0, 10);
      },
      getDefaultEndDate() {
        return new Date().toISOString().slice(0, 10);
      },
  /**
   * 重置页数
   */ 
	reset() {
		this.motMap.pageConfig.pageIndex = 0
		
	},
	/**
	 * 跳转到生产订单详情
	 */
	openDetail(e){
		uni.navigateTo({
			url:'/pages/produce/produceHisDetail?taskBillNo=' + e.fbillno + '&FPRDORGID=' + e.fprdorgid,
			
	})
	},

	/** 上滑加载 */
	handleScrolltolower() {
		if (this.motMap.pageConfig.bottomEnd) return
		this.motMap.pageConfig.pageIndex++
		this.initData()
	},
	/**
	 * 下拉刷新数据
	 */
handleRefresherrefresh() {	
    if (this._refresherTriggered) {
        return;
    }
    // 界面下拉触发，triggered可能不是true，要设为true
    if (!this.refresherTriggered) {
        this.refresherTriggered = true;
    }
    this.reset();
    this._refresherTriggered = true;
    this.motMap.pageConfig.bottomEnd = false;

    // 调用 initData 方法并确保在完成后重置 refresherTriggered 状态
    this.initData().then(() => {
        this.refresherTriggered = false;
        this._refresherTriggered = false;
    }).catch(error => {
        console.error("Error during initData:", error);
        this.refresherTriggered = false;
        this._refresherTriggered = false;
    });
},
	initData({ startDate = '', endDate = '', billNo = ''} = {}) {
	    return new Promise((resolve, reject) => {
	        getMoListHistory({
	            pageSize: this.motMap.pageConfig.pageSize,
	            pageIndex: this.motMap.pageConfig.pageIndex,
	            billNo: this.billNo || "",
	            startDate: this.startDate || "", // 传递开始日期
	            endDate: this.endDate || "", // 传递结束日期
	        }).then(res => {
	            if (res.data.status !== 200) {
	                reject(new Error("API returned non-200 status"));
	                return;
	            }
	            if (this.motMap.pageConfig.pageIndex === 0) this.motMap.taskHistoryList = [];
	            // 遍历返回的数据列表，根据 ftype 设置盒子的颜色
	            res.data.data.dataList.forEach(item => {
	                if (item.ftype === 1) {
	                    item.boxColor = '#faf9de'; // 设置盒子颜色为黄色
	                } else if (item.ftype === 2) {
	                    item.boxColor = '#cce8cf'; // 设置盒子颜色为绿色
	                }
	            });
	            this.motMap.taskHistoryList = this.motMap.taskHistoryList.concat(res.data.data.dataList ?? []);
	            if (res.data.status === 200 && this.motMap.pageConfig.pageSize > res.data.data.dataList.length) {
	                this.motMap.pageConfig.bottomEnd = true;
	            }
	            this.motMap.pageConfig.bottomLoading = false;
	            this.loading = false;
	            this.refresherTriggered = false;
	            this._refresherTriggered = false;
	            this.incompleteCount = res.data.data.completeCount;
	            this.excuteCount = res.data.data.excuteCount;
	            this.completeCount = res.data.data.completeCount;
	
	            resolve();
	        }).catch(err => {
	            console.error('API Error:', err);
	            reject(err);
	        });
	    });
	},
		onSearch() {
		   if (this.startDate && this.endDate) {
		         const startTime = new Date(this.startDate).getTime();
		         const endTime = new Date(this.endDate).getTime();
		   
		         if (startTime > endTime) {
		           uni.showToast({
		             title: '开始时间不能大于结束时间',
		             icon: 'none',
		             duration: 2000
		           });
		           return;
		         }
		       }
		   
		       this.motMap.pageConfig.pageIndex = 0; // 重置分页索引
		       this.initData({
		         startDate: this.startDate,
		         endDate: this.endDate,
		         billNo: this.billNo
				 // cubillNO: this.cubillNO
		       });
		   },
		onStartDateChange(e) {
		    this.startDate = e.detail.value;
		  },
		
		  onEndDateChange(e) {
		    this.endDate = e.detail.value;
		  },
		  
		 
	},
	onLoad() {
		  if (typeof window.entryUrl === 'undefined' || window.entryUrl === ""){
		  	window.entryUrl = location.href.split('#')[0]
		  }
		  let url = /Android/i.test(navigator.userAgent)
		    ? window.location.href
		    : window.entryUrl
		this.getWxConfig(url)
	},
	     mounted() {  
		   this.initData(),
		   this.onSearch()
		 
		    
	     } 
	   };  
</script>


<style lang="scss" scoped>
		@import "../../static/css/common";

.pro-body {
     position: fixed;
     top: 0;
     left: 0;
     right: 0;
     bottom: 0;
     display: flex;
     flex-direction: column;
     background-color: #ffffff;

}
.fixed-header {
    position: fixed;
    top: 30px;
    left: 0;
    right: 0;
    z-index: 100;
    background-color: #fff;
	height: 90px; /* 根据实际高度调整 */
    // // padding: 10px;
    // box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.box-but {
    display: flex;
    align-items: center;
    margin-left: auto;
}
	.picker {
	  padding: 10px;
	  border: 1px solid #ccc;
	  width: 65%;
	  margin-left:10px;
	  margin-top:20px;
	  font-size: 13px; /* 调整输入框文字大小 */
	}
	.uni-form-item {
	  display: flex;
	  align-items: center;
	  margin-bottom: 10px;
	  width: 100%;
	}
	
	.search-box {
		display: flex;
		width: 74%;
		align-items: center;
		border: 1px solid #ccc;
		margin-left:10px;
		margin-top:15px;
	
	}
	.section {  
	    display: flex;  
	    align-items: center; /* 垂直居中 */  
	}  
	 
	.section__title {  
		font-size: 13px;
		margin-left: 4px; /* 给选择器一些空间 */  
	    margin-right: 4px; /* 给选择器一些空间 */  
	}  
	 
	.picker-container {  
	    flex: 1; /* 让选择器占据剩余空间 */  
		font-size: 15px;
	    border: 1px solid #ccc; /* 可选：添加边框以区分 */  
	    padding: 5px; /* 可选：添加内边距 */  
	    border-radius: 4px; /* 可选：圆角 */
		width: 100px; /* 设置选择器容器的宽度 */
	}  
	 
	.picker-text {  
	    display: inline-block; /* 确保文本块级显示 */  
	}
	.search-box1 {  
	    display: flex;  
	    flex-direction: column; /* 如果需要，可以保持整个搜索框的垂直布局 */  
	    align-items: flex-start; /* 根据需要调整垂直对齐 */  
	}  
	.search-row {  
	  display: flex; /* 启用flexbox布局 */  
	  align-items: center; /* 垂直方向上居中对齐子元素 */  
	  width: 100%; /* 设置选择器容器的宽度 */
	}  
	  
	.search-label {  
		margin-top:15px;
	  margin-left: 5px; /* 给选择器一些空间 */
	  margin-right: 5px; /* 给选择器一些空间 */  
	      
	}  
	  
	.search-box2 {  
	margin-top:15px;
	    border: 1px solid #ccc; /* 可选：添加边框以区分 */  
	    padding: 5px; /* 可选：添加内边距 */  
	    border-radius: 4px; /* 可选：圆角 */
		width: 200px; /* 设置选择器容器的宽度 */
	  flex: 1; /* 使搜索框占据剩余的空间 */  
	   flex-basis: auto; /* 基于内容设置初始大小 */  
	      overflow: hidden; /* 防止内容溢出（如果需要的话） */  
	}  

	.search-container {  
	    flex: 1; /* 让容器占据可用空间，但会受到min-width的限制 */  
	    min-width: 200px; /* 设置输入框的最小宽度 */  
	}  
	  
	.uni-input2 { 
	 width: 90%; /* 输入框占据容器的全部宽度 */  
	 flex: 1;
	 padding: 5px;
	 border: none;
	 outline: none;  
	}
	.search-button {  
		margin-top:2px;
	    margin-left: 12px; /* 与输入框保持一定距离 */ 
		margin-right: 5px;
	    // padding: 3px 6px;
		height: 35px;
	
	    border: none;  
	    background-color: #1aad19;  
	    color: white;  
	    border-radius: 4px;  
	    cursor: pointer;  
		width: 70px;
		flex-shrink: 0; /* 防止按钮在宽度不足时被压缩到太小 */  
		  text-align: center; /* 水平居中 */
		  line-height: 35px; /* 垂直居中 */
	}
	.uni-input {
		flex: 1;
		padding: 10px;
		border: none;
		outline: none;
		
	}
	
	.search-icon {
	    cursor: pointer;
	}
	
	.search-icon-image {
	    width: 35px;
	    height: 35px;
		margin-right:10px;
		margin-top:8px;
	}
	.scroll-container {
	     flex: 1;
	    overflow: hidden;
	    overflow-y: auto;
	    -webkit-overflow-scrolling: touch; /* 支持 iOS 上的平滑滚动 */
	  
	}

	.scroll {
    padding-top: 160px; /* 使用 padding-top 替代 margin-top */
    margin-bottom: 20px; /* 根据底部的高度调整 */
    height: calc(100vh - 160px - 1px); /* 根据需要调整高度 */
    position: relative; /* 避免使用 fixed */
    overflow-y: auto; /* 确保内容可以垂直滚动 */
	}
	.uni-list {
	    margin: 10px;
	}
	
	.uni-list-item {
		
	    padding: 15px;
	    border-bottom: 1px solid #ccc;
	}
	
	.uni-list-item:last-child {
	    border-bottom: none;
	}
	
	.uni-list-item[disabled] {
	    color: #ccc;
	    cursor: not-allowed;
	}
	
	
	.title-item {
	    text-align: center;
	    font-weight: bold;
		height: 10px;
	    background-color: #ffffff;
		font-size: 10px;
	}

</style>
